import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import 'Arg.dart' as arg;
import 'dart:math';
import 'OneClass.dart';
import 'Search.dart';


class CommendPage extends StatefulWidget{
  CommendPage({Key key}):super(key:key);
  _CommendPageState createState() => _CommendPageState();
}

class _CommendPageState extends State<CommendPage> with AutomaticKeepAliveClientMixin{
  @override
  bool get wantKeepAlive => true;

  int ShowNum;
  var NetPicUrl;
  var contain = List();
  EasyRefreshController _controller;
  ScrollController _controller_scroll;
  bool showToTopBtn;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ShowNum = 10;
    _controller = EasyRefreshController();
    _controller_scroll = ScrollController();
    this.NetPicUrl = arg.pic_url[Random().nextInt(arg.pic_url.length)];
    showToTopBtn = false;
    _controller_scroll.addListener(() {
      if(_controller_scroll.offset < 1000 && showToTopBtn){
        setState(() {
          this.showToTopBtn = false;
        });
      }
      else if(_controller_scroll.offset >= 1000 && !showToTopBtn){
        setState(() {
          this.showToTopBtn = true;
        });
      }
    });
    getDate();
  }

  void dispose(){
    _controller.dispose();
    _controller_scroll.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body:
        EasyRefresh(
          firstRefresh: true,
          controller: _controller,
          enableControlFinishRefresh: true,
          enableControlFinishLoad: true,
          child: CustomScrollView(
            controller: _controller_scroll,
            slivers: <Widget>[
              SliverAppBar(
                pinned: true,
                elevation: 0,
                expandedHeight: 250,
                flexibleSpace: FlexibleSpaceBar(
                  title: Text('教室推荐'),
                  background: Image.asset(
                    this.NetPicUrl,
                    fit:BoxFit.cover,
                  ),
                ),
                actions: <Widget>[
                  IconButton(
                    icon:Icon(Icons.search),
                    onPressed: (){
                      showSearch(context: context, delegate: searchBarDelegate());
                    },
                  )
                ],
              ),
              SliverFixedExtentList(
                delegate: SliverChildBuilderDelegate(
                        (context,index){
                      return this.contain.length != 0 ?
                      createCard(
                          this.contain[index]['BuildName'],
                          this.contain[index]['Class'],
                          this.contain[index]['MaxNum'],
                          this.contain[index]['Num'],
                          this.contain[index]['Percentage'])
                          :
                      InitialCard();
                    },
                    childCount: this.ShowNum
                ),
                itemExtent: 200,
              )
            ],
          ),

          onLoad: () async {
            await Future.delayed(Duration(seconds: 1),() {
              setState(() {
                this.ShowNum = ShowNum + 5 > this.contain.length ? this.contain.length : this.ShowNum + 5;
              });
            });
            _controller.finishLoad();
          },

          onRefresh: () async {
            await Future.delayed(Duration(seconds: 1),() {
              setState(() {
                this.NetPicUrl = arg.pic_url[Random().nextInt(arg.pic_url.length)];
                getDate();
              });
            });
            _controller.finishRefresh(success: true);
          },
        ),
      floatingActionButton: !showToTopBtn ? null : FloatingActionButton(
          child: Icon(Icons.arrow_upward),
          onPressed: () {
            //返回到顶部时执行动画
            _controller_scroll.animateTo(.0,
                duration: Duration(milliseconds: 200),
                curve: Curves.ease
            );
          }
      ),
    );
  }

  Widget createCard(String BuildName,String ClassName,int MaxNum,int Num,var Percentage){
    return Card(
      elevation: 15.0,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(14.0))),
      child: Column(
        children: [
          ListTile(
              title: Text('${BuildName} ${ClassName}'),
              leading: Icon(
                Icons.school,
                color: Colors.blue,
              ),
              trailing: Icon(
                Icons.arrow_forward_ios,
              ),
              onTap: (){
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => OneClassPage(BuildName, ClassName))
              );
              },
          ),
          Divider(),
          ListTile(
            title: Text('当前人数:${Num}  最大人数:${MaxNum}'),
            leading: Icon(
              Icons.people,
              color: Colors.blue,
            ),
          ),
          ListTile(
            title: Text('百分比:${Percentage}%'),
            leading: Icon(
              Icons.more_vert,
            ),
          )
        ],
      ),
    );
  }

  Widget InitialCard(){
    return Card(
      elevation: 15.0,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(14.0))),
      child: Column(
        children: [
          ListTile(
              title: Text('请刷新~'),
              leading: Icon(
                Icons.school,
                color: Colors.blue,
              )
          ),
          Divider(),
          ListTile(
            title: Text(''),
            leading: Icon(
              Icons.people,
              color: Colors.blue,
            ),
          ),
          ListTile(
            title: Text('百分比: %'),
            leading: Icon(
              Icons.more_vert,
            ),
          )
        ],
      ),
    );
  }

  Future getDate() async{
    var url = 'https://www.fjnu-study.cn/request/inf_request.php?type=AllClass';
    var response = await http.get(url);
    if(response.statusCode == 200){
      var jsonRes = convert.jsonDecode(response.body);
//      print(jsonRes);
//      print(jsonRes is List);
      setState(() {
        this.contain = jsonRes;
        NameTransform();
        this.ShowNum = ShowNum > this.contain.length ? contain.length : ShowNum;
      });
//      print(this.contain);
    }
    else{
      print('请求错误，错误代码：${response.statusCode}');
    }
  }

  void NameTransform(){
    if(this.contain.length > 0){
      for(var i = 0;i < this.contain.length;i++){
        switch(this.contain[i]['BuildName']){
          case 'ZM':{
            this.contain[i]['BuildName'] = '知明';
          }break;
          case 'XD':{
            this.contain[i]['BuildName'] = '笃行';
          }break;
          case 'LC':{
            this.contain[i]['BuildName'] = '立诚';
          }break;
          case 'ZG':{
            this.contain[i]['BuildName'] = '致广';
          }break;
        }
      }
    }
  }
}